package com.mohan.gulimall.product.service.impl;

import com.mohan.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mohan.common.utils.PageUtils;
import com.mohan.common.utils.Query;

import com.mohan.gulimall.product.dao.CategoryDao;
import com.mohan.gulimall.product.entity.CategoryEntity;
import com.mohan.gulimall.product.service.CategoryService;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

  @Autowired
  private CategoryBrandRelationService categoryBrandRelationService;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<CategoryEntity> page = this.page(
            new Query<CategoryEntity>().getPage(params),
            new QueryWrapper<CategoryEntity>()
    );

    return new PageUtils(page);
  }

  @Override
  public List<CategoryEntity> getAllTreeCategory() {
    // 1. 查出所有分类
    List<CategoryEntity> entities = baseMapper.selectList(null);

    // 2. 组装成父子分类
    List<CategoryEntity> level1Menus = entities.stream()
            .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
            .map(menu -> {
              menu.setChildren(getChildrens(menu, entities));
              return menu;
            }).sorted(Comparator
                    .comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
            .collect(Collectors.toList());


    // 2.1 找到一级分类
    return level1Menus;
  }

  @Override
  public void removeMenuByIds(List<Long> asList) {
    //TODO 检测其他地方是否有引用该分类
    baseMapper.deleteBatchIds(asList);
  }

  @Override
  public Long[] findCateLogPath(Long catelogId) {
    List<Long> paths = new ArrayList<>();
    List<Long> catelogParent = findCatelogParent(catelogId, paths);
    // 数组反转
    Collections.reverse(catelogParent);
    return paths.toArray(new Long[paths.size()]);
  }

  @Override
  public void updateDetail(CategoryEntity category) {
    this.updateById(category);
    if (!StringUtils.isEmpty(category.getName()) && !category.getCatId().equals(0L)) {
      categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }
  }

  /**
   * 回调查询path
   * @param catelogId
   * @param paths
   * @return
   */
  private List<Long> findCatelogParent(Long catelogId,List<Long> paths) {
    paths.add(catelogId);
    CategoryEntity categoryEntity = this.getById(catelogId);
    if (categoryEntity.getParentCid() != 0) {
      findCatelogParent(categoryEntity.getParentCid(),paths);
    }
    return paths;
  }

  private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
    List<CategoryEntity> children = all.stream()
            .filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
            .map(categoryEntity -> {
              categoryEntity.setChildren(getChildrens(categoryEntity,all));
              return categoryEntity;
            })
            .sorted(Comparator.comparingInt(menu ->  (menu.getSort() == null ? 0 : menu.getSort())))
            .collect(Collectors.toList());
    return children;
  }
}